import 'package:flutter/material.dart';
import 'package:flutter_study/flutter/_19%E5%B0%8F%E7%BB%84%E4%BB%B6/post.dart';

void main() => runApp(MyApp());

/// 表格控件
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'DataTable数据表格',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        splashColor: Colors.transparent,
      ),
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _sortColumnIndex;

  bool _sortAscending = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('DataTable'),
      ),
      body: Container(
        padding: EdgeInsets.all(12.0),
        child: ListView(
          children: [
            DataTable(
                // 按照哪一行排序，以及排序规则
                sortColumnIndex: _sortColumnIndex,
                sortAscending: _sortAscending,
                columns: [
                  DataColumn(
                      label: Text('Title'),
                      onSort: (index, ascending) {
                        setState(() {
                          _sortColumnIndex = index;
                          _sortAscending = ascending;

                          // 排序
                          posts.sort((a, b) {
                            if (!ascending) {
                              // 交换顺序
                              final c = a;
                              a = b;
                              b = c;
                            }
                            return a.title.length.compareTo(b.title.length);
                          });
                        });
                      }),
                  DataColumn(label: Text('Author')),
                  DataColumn(label: Text('Image')),
                ],
                rows: posts.map((post) {
                  return DataRow(
                    // 行选中状态
                    selected: post.selected,
                    onSelectChanged: (selected) {
                      setState(() {
                        post.selected = selected;
                      });
                    },
                    cells: [
                      DataCell(Text('${post.title}')),
                      DataCell(Text('${post.author}')),
                      DataCell(Image.network(post.imageUrl)),
                    ],
                  );
                }).toList()),
          ],
        ),
      ),
    );
  }
}
